<?php
// 数据库配置
include 'config.php'; 

// 获取订单号
$order_no = isset($_GET['order_no']) ? $_GET['order_no'] : null;

if (empty($order_no)) {
    die('订单号不能为空！');
}

// 检查订单状态是否已为1
$check_sql = "SELECT ty FROM orders WHERE out_trade_no = '$order_no'";
$check_result = $conn->query($check_sql);

if ($check_result->num_rows > 0) {
    $row = $check_result->fetch_assoc();
    if ($row['ty'] == 1) {
        echo "滚"; // 如果订单状态已为1，直接输出提示信息并终止脚本
        exit;
    }
}

// 固定订单号类型为1
$type = "2";

// 构造请求URL
$url = "http://154.64.244.235/pay/chaorder?order_no=$order_no&type=$type";

// 初始化cURL会话
$ch = curl_init();

// 设置cURL选项
curl_setopt($ch, CURLOPT_URL, $url); // 设置请求的URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将curl_exec()获取的信息以文件流的形式返回，而不是直接输出
curl_setopt($ch, CURLOPT_HTTPGET, true); // 设置请求方式为GET

// 执行cURL会话
$response = curl_exec($ch);

// 检查是否有错误发生
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
    exit;
}

// 关闭cURL会话
curl_close($ch);

// 解析响应数据
$response_data = json_decode($response, true);

if ($response_data['code'] == 200 && isset($response_data['data']) && $response_data['data']['status'] == 1) {
    // 更新orders表中的ty字段
    $update_sql = "UPDATE orders SET ty = 1 WHERE out_trade_no = '$order_no'";
    if ($conn->query($update_sql) === TRUE) {
        // 获取订单金额
        $select_sql = "SELECT money, jqr, lxr FROM orders WHERE out_trade_no = '$order_no'";
        $result = $conn->query($select_sql);

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $money = $row['money'];
            $jqr = $row['jqr'];
            $lxr = $row['lxr'];

            // 获取价格设置
            $price_sql = "SELECT monthly_price, yearly_price, lifetime_price FROM price_settings";
            $price_result = $conn->query($price_sql);

            if ($price_result->num_rows > 0) {
                $price_row = $price_result->fetch_assoc();

                if ($money == $price_row['monthly_price']) {
                    $type = 1; // 月卡
                } elseif ($money == $price_row['yearly_price']) {
                    $type = 2; // 年卡
                } elseif ($money == $price_row['lifetime_price']) {
                    $type = 3; // 永久卡
                } else {
                    echo '未知的订单金额';
                    exit;
                }

                // 调用adauth.php接口
                $adauth_url = "http://".$_SERVER['HTTP_HOST']."/api/tj.php?qq=$jqr&lxqq=$lxr&type=$type";
                $adauth_response = file_get_contents($adauth_url);

                echo $response;
            } else {
                echo $response;
            }
        } else {
            echo $response;
        }
    } else {
        echo "订单状态更新失败: " . $conn->error;
        exit;
    }
} else {
    echo $response;
}

// 关闭数据库连接
$conn->close();
?>
